package com.bw.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类描述
 *
 * @author Mr.Wu
 * @create 2020-05-08
 */
@Component
public class MyLB implements LoadBalancer {

	private AtomicInteger atomicInteger = new AtomicInteger(0);


	public final int getAndIncrement() {
		// 当前
		int current;
		// 下一个
		int next;
		do {
			current = this.atomicInteger.get();
			// Integer.MAX_VALUE的值为2147483647
			next = current >= 2147483647 ? 0 : current + 1;
		} while(!this.atomicInteger.compareAndSet(current,next));
		System.out.println("****第几次访问，次数next: " + next);
		return  next;
	}
	/**
	 *
	 * @param serviceInstances 存活的服务器地址列表
	 * @return 具体选择的服务器
	 */
	@Override
	public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
		// getAndIncrement 获取第几次请求
		// serviceInstances.size() 服务器集群总数量
		int index = getAndIncrement() % serviceInstances.size();
		return serviceInstances.get(index);
	}
}
